﻿
using CefSharp;
using CefSharp.WinForms;
using log4net;
using log4net.Repository.Hierarchy;
using MainFrame.Common;
using MainFrame.Common.Interface;
using MainFrame.Plugs;
using MainFrame.Repository;
using Newtonsoft.Json.Linq;
using Qianke.Common;
using Qianke.Common.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static Qianke.Common.Inifile;

namespace MainFrame
{
    /*
     外框架使用场景
    1.管理员后台应用
        a.直接使用  默认启动  启动登录  提示更新/静默更新
    2.自助机应用
        a.首地址appconfig配置  静默更新
     */


    public partial class MainForm : Form
    {

        private ILog logger = LogManager.GetLogger(typeof(MainForm));

        private Common.LocalHttpServer _localServer;


        public string Version = "1.0.0";

        private IniApp appConfig = null;


        /// <summary>
        /// 首页地址
        /// </summary>
        private string _homeUrl = "";


        public ChromiumWebBrowser wb = null;
        


        public MainForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private string machineCode = "";



        /// <summary>
        /// 加载配置
        /// </summary>
        private void LoadConfig()
        {


  
            //_isSilentUpdate = appConfig["IsSilentUpdate"] == "是";
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            var context = SynchronizationContext.Current;
            var th = new Thread(async () =>
            {
                var oldtitle = this.Text;
                try
                {

                    labMessage.Text = "加载配置";
                    //加载配置
                    LoadConfig();


                    //labMessage.Text = "加载插件";
                    //加载插件
                    //LoadPlugs();

                    labMessage.Text = "启动本地Http服务";
                    //启动服务
                    _localServer = new Common.LocalHttpServer(56871);


                    context.Send(a =>
                    {
                        var settings = new CefSettings();

                        //这一块  测试没用
                        //settings.CefCommandLineArgs.Add("enable-system-flash", "1");//启用flash
                        settings.CefCommandLineArgs.Add("enable-media-stream", "1");//启用流媒体
                                                                                    //settings.CefCommandLineArgs.Add("ppapi-flash-version", "25.0.0.171"); //设置flash插件版本
                                                                                    //settings.CefCommandLineArgs.Add("ppapi-flash-path", AppDomain.CurrentDomain.BaseDirectory + "pepflashplayer.dll");
                                                                                    //settings.LogSeverity = LogSeverity.Verbose;
                                                                                    //settings.LogFile = $"LogDir/{DateTime.Now.ToString("yyyyMM")}/{DateTime.Now.ToString("yyyyMMdd")}Cef.txt";
                                                                                    //settings.LocalesDirPath = AppDomain.CurrentDomain.BaseDirectory+"/locales";
                        settings.CefCommandLineArgs.Add("--disable-web-security", "");
                        settings.CefCommandLineArgs.Add("--autoplay-policy", "no-user-gesture-required"); //自动播放视频
                        //if (!string.IsNullOrEmpty(_zoom) && _zoom.LastIndexOf("%") >= 0)
                        //{
                        //    var zoomLevel = _zoom.Substring(0, _zoom.LastIndexOf("%")).ToDouble(0) / 100.0;
                        //    //wb.SetZoomLevel(zoomLevel);
                        //    //wb.BrowserCore.SetZoomLevel(zoomLevel);
                        //    settings.CefCommandLineArgs.Add("--force-device-scale-factor", zoomLevel.ToString());
                        //}
                        
                        settings.CefCommandLineArgs.Add("--disable-site-isolation-trials", "1");
                        settings.CefCommandLineArgs.Add("no-proxy-server", "1");//不使用代理
                        settings.CachePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cache"); //设置缓存目录


                        //必须进行初始化，否则就出来页面啦。
                        if (!Cef.Initialize(settings))
                            MessageBox.Show("初始化失败");
                       // Cef.EnableHighDPISupport();
                    }, null);



                    labMessage.Text = "注册事件";
    
                    context.Send(s =>
                    {
                        wb = new ChromiumWebBrowser(_homeUrl);
                        Controls.Add(wb);            //加入到当前窗体中
                    }, null);
                    //实例化控件
                    labMessage.Text = "加载首页";
                    //var wb = new ChromiumWebBrowser(_homeUrl);
                    wb.Load(_homeUrl);
                    wb.RequestHandler = new CefWebRequestHandler();

                    wb.Dock = DockStyle.Fill;            //设置停靠方式
                    wb.MenuHandler = new MenuHandler() { MainForm = this };
                    wb.DownloadHandler = new DownloadHandler();

                    //bool bFirstLoad = true;
                    //wb.LoadingStateChanged += (s, ee) =>
                    //{
                    //    if (!ee.IsLoading)
                    //    {
                            
                    //    }
                    //};

                    Controls.Remove(labMessage);
                    labMessage.Text = "添加控件";

                    var db = new MFContext();

                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                    MessageBox.Show("初始化遇到异常:" + ex.Message);
                    Environment.Exit(0);
                }
                Text = oldtitle;
            });
            th.Start();
        }




        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (_localServer != null)
                    _localServer.Close();
            }
            catch
            {

            }
        }



    }
}
